package com.wei.lawyer.ui.activity;

import android.os.Bundle;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.wei.lawyer.App;
import com.wei.lawyer.R;
import com.wei.lawyer.model.CaseBean;
import com.wei.lawyer.model.ProvinceBean;
import com.wei.lawyer.model.WebDataBean;
import com.wei.lawyer.net.presenter.HomePresenter;
import com.wei.lawyer.ui.adapter.BaseDelegateAdapter;
import com.wei.lawyer.ui.adapter.BaseViewHolder;
import com.wei.lawyer.utils.RxUtils;
import com.wei.lawyer.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者：赵若位
 * 时间：2018/11/14 15:52
 * 邮箱：1070138445@qq.com
 * 功能：案件委托
 */
public class CaseActivity extends BaseActivity<HomePresenter>
{
    @Bind(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private TextView mTvCity;
    private EditText mEdPhone;


    private DelegateAdapter mAdapter;
    private BaseDelegateAdapter mProcessAdapter, mPayAdapter;


    /*地址选择器*/
    private List<ProvinceBean> options1Items = new ArrayList<>();
    private List<List<String>> options2Items = new ArrayList<>();
    private OptionsPickerView mLocationPickView;

    private CaseBean mData;




    @Override
    protected int getLayoutResource()
    {
        return R.layout.activity_case;
    }

    @Override
    protected void setStatusBarColor()
    {

    }

    @Override
    protected HomePresenter createPresenter()
    {
        return new HomePresenter(this, this);
    }


    @Override
    protected void initView(Bundle savedInstanceState)
    {
        super.initView(savedInstanceState);
        setLeftBack();
        setTitle(getString(R.string.tv_home_case));

        VirtualLayoutManager manager = new VirtualLayoutManager(mActivity);
        manager.setInitialPrefetchItemCount(3);
        mRecyclerView.setLayoutManager(manager);
        //关闭动效提升效率
        ((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        mRecyclerView.setItemViewCacheSize(3);

        mAdapter = new DelegateAdapter(manager);
        mRecyclerView.setAdapter(mAdapter);
        initAdapter();


        setLocationPickData();
    }

    /*设置适配器*/
    private void initAdapter()
    {
        //流程
        mProcessAdapter = new BaseDelegateAdapter<String>(this, R.layout.layout_case_process)
        {
            @Override
            public void convert(BaseViewHolder holder, int position, String s)
            {
                mTvCity = holder.getView(R.id.tv_city);
                mEdPhone = holder.getView(R.id.ed_phone);
                final EditText descript = holder.getView(R.id.et_descript);
                final TextView count = holder.getView(R.id.tv_count);
                descript.addTextChangedListener(new TextWatcher()
                {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after)
                    {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count)
                    {

                    }

                    @Override
                    public void afterTextChanged(Editable s)
                    {
                        StringBuilder builder = new StringBuilder();
                        builder.append(descript.getText().toString().length())
                                .append("/100");
                        count.setText(builder);
                    }
                });

                holder.setText(getString(R.string.tv_please_check), R.id.tv_city)
                        .setOnClickListener(R.id.tv_city, new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                                if (mLocationPickView != null)
                                {
                                    mLocationPickView.show();
                                }
                            }
                        });
            }
        };
        mAdapter.addAdapter(mProcessAdapter);
        mProcessAdapter.setData("");

        //支付方式
        mPayAdapter = new BaseDelegateAdapter<CaseBean>(this, R.layout.layout_case_pay_type)
        {
            @Override
            public void convert(BaseViewHolder holder, int position, CaseBean data)
            {
                //设置收费标准
                StringBuilder builder = new StringBuilder();
                builder.append(getString(R.string.tv_money))
                        .append(data.getPrice() / 100);
                holder.setText(builder.toString(), R.id.tv_price)
                        .setImageResource(R.mipmap.radio_bg_2, R.id.img_pay_urgent)
                        .setText(data.getPriceNote(), R.id.tv_descript);
                //设置加急UI样式
                setUrgentUi((TextView) holder.getView(R.id.tv_pay_urgent_descript_1));
            }


            //异步设置平台加急UI样式
            private void setUrgentUi(final TextView view)
            {
                if (view != null)
                {
                    Observable.create(new ObservableOnSubscribe<SpannableString>()
                    {
                        @Override
                        public void subscribe(ObservableEmitter<SpannableString> e) throws Exception
                        {
                            String price = String.valueOf(App.mConfig != null ? App.mConfig.getUrgentChatPrice() / 100 : 0);
                            String descript = getString(R.string.tv_urgent_descript_1).replace("Price", price);
                            SpannableString span = new SpannableString(descript);
                            ForegroundColorSpan title = new ForegroundColorSpan(getResources().getColor(R.color.textTitle));
                            span.setSpan(title, 0, descript.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
                            ForegroundColorSpan color = new ForegroundColorSpan(getResources().getColor(R.color.price));
                            span.setSpan(color, 2, 3 + price.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                            e.onNext(span);
                            e.onComplete();
                        }
                    }).compose(RxUtils.<SpannableString>rxObservableSchedlers())
                            .compose(mActivity.<SpannableString>bindUntilEvent(ActivityEvent.DESTROY))
                            .subscribe(new Consumer<SpannableString>()
                            {
                                @Override
                                public void accept(SpannableString span) throws Exception
                                {
                                    view.setText(span);
                                }
                            });
                }
            }


        };
        mAdapter.addAdapter(mPayAdapter);
        mPayAdapter.setData(new CaseBean());
    }


    /*获取省市区三级联动数据源*/
    private void setLocationPickData()
    {
        Flowable.create(new FlowableOnSubscribe<List<ProvinceBean>>()
        {
            @Override
            public void subscribe(FlowableEmitter<List<ProvinceBean>> e) throws Exception
            {
                Gson gson = new Gson();
                String json = StringUtils.getJson(mActivity, "City.json");
                options1Items = gson.fromJson(json, new TypeToken<List<ProvinceBean>>()
                {
                }.getType());
                e.onNext(options1Items);
                e.onComplete();
            }
        }, BackpressureStrategy.BUFFER)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .map(new Function<List<ProvinceBean>, List<List<String>>>()
                {
                    @Override
                    public List<List<String>> apply(List<ProvinceBean> list) throws Exception
                    {
                        for (ProvinceBean data : list)
                        {
                            List<String> cities = new ArrayList<>();
                            for (ProvinceBean.CityBean city : data.getCity())
                            {
                                cities.add(city.getName());
                            }
                            options2Items.add(cities);
                        }
                        return options2Items;
                    }
                })
                .compose(this.<List<List<String>>>bindUntilEvent(ActivityEvent.DESTROY))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<List<String>>>()
                {
                    @Override
                    public void accept(List<List<String>> lists) throws Exception
                    {
                        mLocationPickView = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener()
                        {
                            @Override
                            public void onOptionsSelect(int options1, int options2, int options3, View v)
                            {
                                StringBuilder builder = new StringBuilder();
                                builder.append(options1Items.get(options1).getPickerViewText())
                                        .append(" ")
                                        .append(options2Items.get(options1).get(options2));
                                if (mTvCity != null)
                                {
                                    mTvCity.setText(builder);
                                }
                            }
                        }).setSubCalSize(20)
                                .setCancelText(getString(R.string.tv_cancel))
                                .setSubmitText(getString(R.string.tv_submit))
                                .setContentTextSize(20).build();
                        mLocationPickView.setPicker(options1Items, options2Items);
                    }
                });
    }


    @Override
    protected void initData()
    {
        super.initData();
        mPresenter.getCaseData();
    }

    @Override
    public void showData(Object o)
    {
        super.showData(o);
        if (o instanceof CaseBean)
        {
            mData = (CaseBean) o;
            mPayAdapter.setData(mData);
        }
    }

    @OnClick({R.id.img_wen, R.id.tv_kefu, R.id.tv_action})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.img_wen:
                WebDataBean data = new WebDataBean();
                data.setTitle(mData.getTitle());
                data.setDescript(mData.getContent());
                openActivity(DescriptActivity.class, data);
                break;
            case R.id.tv_kefu:
                //TODO 客服
                break;
            case R.id.tv_action:
                if (mTvCity != null && mEdPhone != null)
                {
                    String city = mTvCity.getText().toString();
                    if (city.equals(getString(R.string.tv_please_check)))
                    {
                        alert(getString(R.string.alert_check_city));
                        return;
                    }

                    String phone = mEdPhone.getText().toString();
                    if (TextUtils.isEmpty(phone) || (!StringUtils.isMobile(phone)))
                    {
                        alert(getString(R.string.alert_enter_phone));
                        return;
                    }

                    alert(getString(R.string.alert_send_case_order_success));
                    doFinish(200);
                }
                break;
            default:
                break;
        }
    }
}
